<?php

require_once(APPPATH . 'libraries/MY_PortalController.php');

class Login extends MY_PortalController {

	function Login() {
		parent::MY_PortalController();
	}

	function index() {
		$this->mainLogin("xo");
	}

	function mainLogin($pc_type) {
		$user = $this->getUserLogued();
		if($user == NULL){
			if ($pc_type == 'xo' || $pc_type == 'pc') {
				$data = array("pc_type" => $pc_type);
				$this->load->view("login", $data);
			} else {
				show_404('login');
			}
		}else{
			$this->setDestination($user,$pc_type);
		}
	}

	function userLogin() {
		$this->load->model('m_user');
		$login = $this->input->post('login');
		$passwd = sha1($this->input->post('paswd'));
		$user = $this->m_user->getUserFromLogin($login);
		$ok = false;
		$msg = "";
		if ($user === NULL) {
			//TODO crear al usuario cheaquendo que venga con la ip de ceibal?
			//Se crea el nuevo usuario y canal
			try {
				$this->db->trans_begin();
				//User
				$user = new User();
				$user->nick = 'Usuario';
				$user->login = $login;
				$user->password = $passwd;
				$user->is_admin = 0;

				$user->id = $this->m_user->create($user);

				//Ends saccessfully the transaction
				$this->db->trans_commit();
				$ok = true;
			} catch (Exception $e) {
				$this->db->trans_rollback();
				$msg = "Generic error " . $e->getMessage();
			}
		} else {
			if ($user->password == $passwd) {
				$ok = true;
			} else {
				$msg = "Usuario o contraseña incorrectos";
			}
		}

		$pc_type = $this->input->post("pc_type");

		if ($ok) {
			if ($user->suite_cert_cn == NULL) {
				try {
					$this->load_api();
					$response = $this->api->create_certificate(2, $user->id);
					$user->suite_cert_cn = $response['certificate_cn'];
					$this->m_user->update($user);
				} catch (Exception $ex) {
					$ok = false;
					$msg = "No se pudo crear el certificado para el usuario";
				}
			}
			if ($ok) {
				$this->setUserLogued($user);
			} else {
				$this->load->view($pc_type . "/login");
			}
		}

		if ($ok) {
			$this->setDestination($user,$pc_type);
		} else {
			$this->session->set_flashdata('login_error', $msg);
			redirect("main/$pc_type");
		}
	}

	function setDestination(User $user,$pc_type){
		if($user->is_admin){
			redirect("backend/admin");
		}else{
			redirect("player/$pc_type");
		}
	}

}

?>
